<template>
  <div class="cluster-main-content">
    <div style="width: 40%">
      <el-select class="buy-house-type-select" v-model="buyHouseType" size="small"
                 @change="(event) => changeBuyHouseType(event)">
        <el-option
            v-for="item in buyHouseTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            class="custom-select-option"
        />
      </el-select>
      <div ref="echartDom" style="width: 100%" v-bind="$attrs"></div>
    </div>
    <div style="margin-left: 15px;">
      <el-select class="cluster-sort-select" v-model="clusterSort" size="small"
                 @change="(event) => changeClusterSort(event)">
        <el-option
            v-for="item in [
                {
                  label: '由高到低',
                  value: 'desc'
                },
                {
                  label: '由低到高',
                  value: 'asc'
                },
            ]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            class="custom-select-option"
        />
      </el-select>
      <div class="chart-info" v-if="colors?.length" :style="{...magnifyFontSizeObj}">
        <div class="chart-info-item" v-for="(item, index) of pieData" :key="index">
          <div class="name"><div class="circle-before-name" :style="{ backgroundColor: colors[index] }" />{{ item.name }}（{{ item.value }}%）</div>
          <div class="children-name" v-for="(childrenItem, childrenIndex) of item.children" :key="childrenIndex">{{ childrenItem.name }} 占比:{{ childrenItem.percentage }}%</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose, nextTick} from 'vue'
import {pxToRem, getRandomColor} from "@/utils/index";

const props = defineProps({
  pieData: {
    type: Array,
    default: () => []
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  },
});

const echartDom = ref(null);
const myChart = shallowRef(null);
const echarts = inject('echarts');

const colors = ref([])

const buyHouseType = ref('全部购房')
const buyHouseTypeOptions = ref([
  {
    id: 1,
    label: '全部购房',
    value: '全部购房'
  },
  {
    id: 1,
    label: '首套购房',
    value: '首套购房'
  },
  {
    id: 1,
    label: '二套购房',
    value: '二套购房'
  },
  {
    id: 1,
    label: '多套购房',
    value: '多套购房'
  },
  {
    id: 1,
    label: '卖旧买新',
    value: '卖旧买新'
  },
])
const clusterSort = ref('desc')

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let totalValue = 0
    let tempDataList = props?.pieData
    for (let i = 0; i < tempDataList.length; i++) {
      totalValue += tempDataList[i].value;
    }
    let textObj = {
      name: props?.pieData[0]?.name,
      percentage: props?.pieData[0]?.percentage
    }
    colors.value = []
    props?.pieData?.forEach(x => {
      const tempColor = getRandomColor();
      colors.value.push(tempColor)
    })
    let option = {
      color: colors.value,
      title: {
        text: `{b|${textObj.percentage}%}\n\n${textObj.name}`,
        textAlign: 'center',
        triggerEvent: true,
        textStyle: {
          color: 'white',
          fontSize: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 15 : 20),
          width: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 100 : 150),
          rich: {
            b: {
              align: "center",
              fontSize: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 18 : 26),
              padding: [0, 0, 0, pxToRem(8 * props?.dialogData?.fontSizeTimes)]
            }
          },
          overflow: 'truncate', // 文本溢出时显示省略符号
          ellipsis: '...', // 使用的省略符号
        },
        tooltip: {
          show: true,
          formatter: (res) => {
            return `111`;
          }
        },
        x: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 70 : 95),
        y: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 100 : 215),
      },
      tooltip: {
        show: true,
      },
      series: [
        {
          type: 'pie',
          radius: [`${props?.dialogData?.fontSizeTimes == 1 ? 70 : 70}%`, `${props?.dialogData?.fontSizeTimes == 1 ? 95 : 95}%`],
          center: ['50%', 'center'],
          clockwise: true,
          zIndex: 1,
          avoidLabelOverlap: true,
          label: {
            show: false,
          },
          labelLine: {
            //label线的长度
            show: false,
          },
          itemStyle: {
            normal: {
              borderWidth: pxToRem(5),
            }
          },
          data: props?.pieData
        }
      ]
    }
    option && myChart.value.setOption(option, true);

    // 鼠标移入事件
    myChart.value.on('mouseover', function (params) {
      if (params?.componentType === 'series') {
        textObj.name = params?.data.name
        textObj.percentage = params?.data.percentage
        myChart.value.setOption({
          title: {
            text: `{b|${textObj.percentage}%}\n\n${textObj.name}`,
          }
        })
      }
    });
  }
}

const magnifyFontSizeObj = ref({
  '--custom-font-size-12': pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 12 : 20) + 'px',
})

const changeFontSize = () => { // 动态改变字体大小方法
  magnifyFontSizeObj.value = {
    '--custom-font-size-12': pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 12 : 20) + 'px',
  }
}

const changeBuyHouseType = (val) => {
  console.log(val);
}

const changeClusterSort = (val) => {
  console.log(val);
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  changeFontSize();
  initEchart();
};

defineExpose({
  updateChart
})

onMounted(() => {
  nextTick(() => {
    initEchart();
  })
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h220 {
  width: 370px;
  height: 250px;
}
.dialog-h220 {
  width: 500px;
  height: 490px;
}

.cluster-main-content {
  display: flex;
  .buy-house-type-select {
    width: 60%;
  }
  .cluster-sort-select {
    width: 50%;
    margin-bottom: 10px;
  }
  .chart-info {
    overflow-y: auto;
    height: 100%;
    font-size: var(--custom-font-size-12);
    color: white;
    .chart-info-item {
      margin-bottom: 5px;
      .name {
        display: flex;
        align-items: center;
        .circle-before-name {
          width: 10px;
          height: 10px;
          margin-right: 5px;
          border-radius: 50%;
        }
      }
    }
  }
}
.custom-select-option{
  color:#ffffff;
  background: #1C5BCC;
}
.custom-select-option.is-selected{
  color: #00e0ff;
}
.custom-select-option:hover{
  background:#368CF2;
}
</style>